<template>
  <div class="user-login-info">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="header-title">用户登录信息</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户ID或IP地址"
              clearable
              style="width: 250px; margin-right: 10px;"
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button :icon="Refresh" @click="fetchLoginInfo">刷新</el-button>
          </div>
        </div>
      </template>

      <el-table 
        :data="paginatedLoginInfo" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <el-table-column label="用户ID" prop="userId" width="100" align="center"></el-table-column>
        <el-table-column label="用户名" prop="username" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="IP地址" prop="ipAddress" width="150"></el-table-column>
        <el-table-column label="操作系统" prop="os" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="设备" prop="device" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="浏览器" prop="browser" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="登录地点" prop="location" min-width="150" show-overflow-tooltip></el-table-column>
        <el-table-column label="状态" prop="status" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="登录时间" prop="loginTime" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.loginTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              :icon="Delete"
              @click="deleteLoginInfo(row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete } from '@element-plus/icons-vue';

export default {
  name: 'UserLoginInfo',
  components: {
    Search,
    Refresh,
    Delete
  },
  data() {
    return {
      allLoginInfo: [], // 存储所有数据
      filteredLoginInfo: [], // 过滤后的数据
      paginatedLoginInfo: [], // 分页后的数据
      loading: false,
      searchKeyword: '',
      currentPage: 1,
      pageSize: 20,
      total: 0
    };
  },
  mounted() {
    this.fetchLoginInfo();
  },
  methods: {
    async fetchLoginInfo() {
      this.loading = true;
      try {
        const res = await axios.get('http://localhost:8080/api/admin/user-login-info/list');
        if (res.data.code === 200) {
          this.allLoginInfo = res.data.data || [];
          this.handleSearch();
        } else {
          ElMessage.error(res.data.msg || '获取登录信息失败');
        }
      } catch (error) {
        console.error('获取登录信息失败:', error);
        ElMessage.error('获取登录信息失败：' + (error.message || '网络错误'));
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      if (!this.searchKeyword) {
        this.filteredLoginInfo = [...this.allLoginInfo];
      } else {
        const keyword = this.searchKeyword.toLowerCase();
        this.filteredLoginInfo = this.allLoginInfo.filter(item => {
          return (
            String(item.userId).includes(keyword) ||
            (item.ipAddress && item.ipAddress.toLowerCase().includes(keyword)) ||
            (item.username && item.username.toLowerCase().includes(keyword))
          );
        });
      }
      this.total = this.filteredLoginInfo.length;
      this.currentPage = 1;
      this.applyPagination();
    },
    applyPagination() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      this.paginatedLoginInfo = this.filteredLoginInfo.slice(start, end);
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.applyPagination();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.applyPagination();
    },
    async deleteLoginInfo(id) {
      try {
        await ElMessageBox.confirm('确定要删除这条登录信息吗？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        });

        const res = await axios.delete(`http://localhost:8080/api/admin/user-login-info/delete/${id}`);
        if (res.data.code === 200) {
          ElMessage.success('删除成功');
          this.fetchLoginInfo();
        } else {
          ElMessage.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除登录信息失败:', error);
          ElMessage.error('删除失败：' + (error.message || '网络错误'));
        }
      }
    },
    formatTime(time) {
      if (!time) return '-';
      const date = new Date(time);
      if (isNaN(date.getTime())) return time;
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>

<style scoped>
.user-login-info {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
    gap: 10px;
  }

  .header-actions .el-input {
    width: 100% !important;
    margin-right: 0 !important;
  }
}
</style>
